package com.yuanchu.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanchu.common.utils.PageResult;
import com.yuanchu.goods.dao.YoshopCommentDao;
import com.yuanchu.goods.dto.QueryCommentParamsDto;
import com.yuanchu.goods.entity.YoshopCommentEntity;
import com.yuanchu.goods.entity.YoshopGoodsEntity;
import com.yuanchu.goods.service.YoshopCommentService;
import com.yuanchu.goods.service.YoshopGoodsService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;


@Service("yoshopCommentService")
public class YoshopCommentServiceImpl extends ServiceImpl<YoshopCommentDao, YoshopCommentEntity> implements YoshopCommentService {


    @Resource
    private YoshopGoodsService goodsService;


    @Override
    public PageResult<YoshopCommentEntity> queryCommentParams(QueryCommentParamsDto params) {

        LambdaQueryWrapper<YoshopCommentEntity> lqw = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(params.getGoodsName())){
            // 根据商品名称获取商品集合
            List<YoshopGoodsEntity> goodsEntities = goodsService.list(new QueryWrapper<YoshopGoodsEntity>().eq("goods_name", params.getGoodsName()));
            if (CollectionUtils.isNotEmpty(goodsEntities)){
                lqw.in(YoshopCommentEntity::getGoodsId, goodsEntities.stream().map(YoshopGoodsEntity::getGoodsId).collect(Collectors.toList()));
            }
        }
        // 根据订单编号查询
        lqw.eq(params.getOrderId() != null, YoshopCommentEntity::getOrderId, params.getOrderId());
        // 根据用户id查询
        lqw.eq(params.getUserId() != null, YoshopCommentEntity::getUserId, params.getUserId());
        // 根据状态查询
        if (params.getStatus() != null && params.getStatus() > 0 ){
            lqw.eq(YoshopCommentEntity::getStatus, params.getStatus());
        }
        // 根据商品评价查询
        lqw.eq(params.getScore() != null, YoshopCommentEntity::getScore, params.getScore());

        Page<YoshopCommentEntity> page = this.page(new Page<>(params.getPage(), params.getLimit()));
        Page<YoshopCommentEntity> pageResult = this.page(page, lqw);
        return PageResult.formatPageResult(pageResult.getRecords(), params.getPage(), params.getLimit(), pageResult.getTotal());
    }

    @Override
    public List<YoshopCommentEntity> queryAllComments() {
        return this.list();
    }


}